package logic

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"log"
	"shenzhou/C/srv/model/es"

	"shenzhou/C/srv/internal/svc"
	"shenzhou/C/srv/shenzhou"

	"github.com/zeromicro/go-zero/core/logx"
)

type SearchGoodsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSearchGoodsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchGoodsLogic {
	return &SearchGoodsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SearchGoodsLogic) SearchGoods(in *shenzhou.SearchGoodsRequest) (*shenzhou.GoodsListResponse, error) {
	// todo: add your logic here and delete this line
	query := map[string]interface{}{}
	if in.KeyWord == "" {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match_all": map[string]interface{}{},
			},
		}
	} else {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{
					"GoodsTitle": in.KeyWord,
				},
			},
		}
	}
	var buf bytes.Buffer

	if err := json.NewEncoder(&buf).Encode(query); err != nil {
		log.Fatalf("Error encoding query: %s", err)
	}

	// Perform the search request.
	res, err := es.Es.Search(
		es.Es.Search.WithContext(context.Background()),
		es.Es.Search.WithIndex("goods"),
		es.Es.Search.WithBody(&buf),
		es.Es.Search.WithTrackTotalHits(true),
		es.Es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()
	fmt.Println(res)
	var r map[string]interface{}
	json.NewDecoder(res.Body).Decode(&r)
	var goodsList []*shenzhou.GoodsItem
	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		source := hit.(map[string]interface{})["_source"].(map[string]interface{})

		goodsList = append(goodsList, &shenzhou.GoodsItem{
			GoodsId:    int64(source["ID"].(float64)),
			GoodsTitle: source["GoodsTitle"].(string),
			GoodsCover: source["GoodsCover"].(string),
			GoodsPrice: float32(source["GoodsPrice"].(float64)),
		})
	}

	return &shenzhou.GoodsListResponse{GoodsList: goodsList}, nil
}
